package com.cloudlead.common.lang.persistence;

import com.cloudlead.common.lang.BaseBean;
import com.cloudlead.common.lang.annotation.Label;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 分页请求实现
 * <p>
 * User: dean.lu Date: 13-9-9 Time: 上午10:35
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@Label("分页条件")
public class PageRequest implements BaseBean {
    private static final long serialVersionUID = 8280485938848398236L;

    @NotNull
    @Label("页码")
    private int page;
    @NotNull
    @Min(1)
    @Label("页大小")
    private int size;
    @Valid
    @Label("排序")
    private Sort sort;
    @Valid
    @Label("查询条件")
    Filter filter;

    public PageRequest() {
        this(0, 0, null, null);
    }

    public PageRequest(int page, int size) {
        this(page, size, null, null);
    }

    public PageRequest(int page, int size, Sort sort) {
        this(page, size, sort, null);
    }

    public PageRequest(int page, int size, Sort sort, Filter filter) {
        super();
        this.page = page;
        this.size = size;
        this.sort = sort;
        this.filter = filter;
    }

    public Sort getSort() {
        return sort;
    }

    public int getPage() {
        return page <= 0 ? 1 : page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public void setSort(Sort sort) {
        this.sort = sort;
    }

    public int getOffset() {
        return (getPage() - 1) * getSize();
    }

    public Filter getFilter() {
        return filter;
    }

    public void setFilter(Filter filter) {
        this.filter = filter;
    }

    @Override
    public boolean equals(final Object obj) {

        if (this == obj) {
            return true;
        }

        PageRequest that = (PageRequest) obj;

        boolean pageEqual = this.page == that.page;
        boolean sizeEqual = this.size == that.size;

        boolean sortEqual = this.sort == null ? that.sort == null : this.sort
                .equals(that.sort);

        return pageEqual && sizeEqual && sortEqual;
    }

    @Override
    public int hashCode() {

        int result = 17;

        result = 31 * result + page;
        result = 31 * result + size;
        result = 31 * result + (null == sort ? 0 : sort.hashCode());

        return result;
    }

    @Override
    public String toString() {
        return "{ page=" + getPage() + ", size=" + size + ", sort=" + sort
                + ", filter=" + filter + " }";
    }

}
